<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="坯布编号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :allowClear="true" @search="handleSearch"
                  v-model="pageData.greyCode" :filter-option="false" :loading="loading4" allow-search
                  @focus="focusSel">
                  <a-option v-for="item in pageData.nameOpen1" :value="item['greyCode']">{{ item['greyCode']
                  }}
                  </a-option>
              </a-select> -->
              <a-input
                class="bacClass"
                :style="{ width: '200px' }"
                v-model="pageData.greyCode"
                :allowClear="true"
              ></a-input>
            </a-form-item>
            <a-form-item label="坯布名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :allowClear="true"
                  @search="handleSearch1" v-model="pageData.greyName" :filter-option="false"
                  :loading="loading1" allow-search @focus="focusSel1">
                  <a-option v-for="item in pageData.nameOpen2" :value="item['grayFabricName']">{{
                      item['grayFabricName']
                  }}
                  </a-option>
              </a-select> -->
              <a-input
                class="bacClass"
                :style="{ width: '200px' }"
                v-model="pageData.greyName"
                :allowClear="true"
              ></a-input>
            </a-form-item>
            <a-form-item label="状态">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '200px' }"
                v-model="pageData.state"
                allow-search
              >
                <a-option :value="0">未录入</a-option>
                <a-option :value="1">已录入</a-option>
                <a-option :value="2">全部</a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar" style="float: right">
          <Toolbar
            :items="pageData.btnList"
            @export="exports"
            @import="importHandler"
            @select="selectHandler"
            @excel="downloadHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true"
          rowSelection="multiple"
          :localeText="localeText1"
          @grid-ready="gridReady"
          style="height: 100%"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :page-size-options="pagingList1"
    />
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      unmount-on-close
      popup-container=".arco-tabs-content"
      height="100%"
      :visible="pageData.showAdd"
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      :ok-loading="pageData.pageLoading"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label="常见疵点" label-col-flex="100px">
            <a-select
              popup-container="html"
              class="bacClass"
              multiple
              :allowClear="true"
              @search="handleSearchopen7"
              v-model="dataForm.defect"
              :filter-option="false"
              allow-search
              @focus="focusSelopen7"
            >
              <a-option v-for="item in pageData.nameOpen7" :value="item['defectName']"
                >{{ item['defectName'] }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="接机前">
            <a-textarea
              class="bacClass"
              v-model="dataForm.beforeDefect"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
          <a-form-item label-col-flex="100px" label="接机后">
            <a-textarea
              class="bacClass"
              v-model="dataForm.afterDefect"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
          <a-form-item label-col-flex="100px" label="敏感布">
            <a-select class="bacClass" v-model="dataForm.isSensitive">
              <a-option :value="1">是</a-option>
              <a-option :value="0">否</a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import { localeText } from '@/api/aggridZw'
  import { ref, reactive, onMounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal, Pagination } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import emitter from '@/hooks/useEventBus'
  import validate from '@/hooks/useValidate'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  
  import { pagingList } from '@/api/paging'
  import { EXELTABLE } from '@/utils/exportEXCEL'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  interface ClothInfo {
    defect: any
    afterDefect: any
    beforeDefect: any
    isSensitive: any
  }

  export default {
    name: 'PreventiveMeasure',
    setup() {
      const dataForm = reactive<ClothInfo>({
        defect: '',
        beforeDefect: '',
        afterDefect: '',
        isSensitive: '',
      })
      const headerShow = ref<boolean>(true)
      //查询
      const scrollbar = ref(true)

      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      const total = ref(0)
      const page = ref(1)
      const size = ref(10)

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }

      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'planSingle/greyDefect/getGreyDefect',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            greyCode: pageData.greyCode,
            greyName: pageData.greyName,
            state: pageData.state,
            // greyCloth: pageData.dropDownData,
            // adjustmentTypeName: pageData.dropDownData1,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              //pagination.setTotalSize(data.total);
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //检验表单是否含有中文的方法
      const hasChiese = validate.includeChinese
      const tableColumns = useTableColumn([
        {
          title: '坯布编号',
          key: 'greyCode',
          dataIndex: 'greyCode',
          width: 150,
        },
        {
          title: '坯布名称',
          key: 'greyName',
          dataIndex: 'greyName',
          width: 150,
        },
        {
          title: '寸数',
          key: 'dimensionFigure',
          dataIndex: 'dimensionFigure',
          width: 150,
        },

        {
          title: '设备机型',
          key: 'machineType',
          dataIndex: 'machineType',
          width: 150,
        },
        {
          title: '常见疵点',
          key: 'defect',
          dataIndex: 'defect',
          width: 150,
        },
        {
          title: '接机前',
          key: 'beforeDefect',
          dataIndex: 'beforeDefect',
          width: 150,
        },
        {
          title: '接机后',
          key: 'afterDefect',
          dataIndex: 'afterDefect',
          width: 150,
        },
        {
          title: '敏感布',
          key: 'isSensitive',
          dataIndex: 'isSensitive',
          width: 150,
        },
        // {
        //     title: "状态",
        //     key: "state",
        //     dataIndex: "state",
        //     slotName: "action1",
        //     width: 150, fixed: 'right'
        // },
        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ])

      const scroll = {
        x: 2000,
        y: 200,
      }

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
        }
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 220
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <el-tag v-if="state == 0" type="dashed" class="gesture">未录入</el-tag>
              <el-tag v-if="state == 1" type="success" class="gesture">已录入</el-tag>
              <el-button style="color:#165dff;" @click="a" class="gesture" link v-if="isEdit">修改</el-button>
            </a-space>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
                state: props.params.data.state,
                isEdit: pageData.isEdit,
              }
            },
          }
        }
        if (o.slotName === 'action1') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 110
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <el-tag v-if="state == 0" type="dashed" class="gesture">未录入</el-tag>
              <el-tag v-if="state == 1" type="success" class="gesture">已录入</el-tag>
            </a-space>`,
            setup(props: any) {
              return {
                state: props.params.data.state,
              }
            },
          }
        }

        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)

      const tablediv = ref(null)
      const pageData = reactive<{
        showAdd: boolean
        pageLoading: boolean
        greyCode: any
        greyName: any
        state: any
        nameOpen7: any
        nameOpen2: any
        nameOpen1: any
        sideTitle: any
        rHeight: number | undefined
        dropDownData: any
        btnList: any
        isEdit: boolean
      }>({
        showAdd: false,
        pageLoading: false,
        greyCode: '',
        greyName: '',
        state: 2,
        nameOpen7: [],
        nameOpen2: [],
        nameOpen1: [],
        sideTitle: '修改',
        rHeight: 0,
        dropDownData: '',
        btnList: [],
        isEdit: false,
      })

      onMounted(() => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight

        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
        window.addEventListener('resize', () => {
          pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
          //弹出层的高
          if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 100
          }
        })
        doRefresh()
      })
      let cxbl = ''
      //查询
      const selectHandler = () => {
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增调机类型'
      }

      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }

      const formRef = ref<FormInstance>()
      const sideOk = () => {
        if (dataForm.defect != '') {
          dataForm.defect = dataForm.defect.join().replace(/^\s*,/, '')
          // dataForm.defect = dataForm.defect.replace(/^\s*,/, "");
        } else {
          dataForm.defect = ''
        }
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true
            post({
              url: 'planSingle/greyDefect/update',
              data: dataForm,
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                  dataForm.defect = dataForm.defect.split(',')
                }
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows() === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: '/qms/AdjustmentType/delete',
              //data: selectedRowKeys.value,
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, message }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })

                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const editHandler = (record: ClothInfo) => {
        for (var key in record) {
          dataForm[key] = record[key]
        }
        dataForm.isSensitive = dataForm.isSensitive === '是' ? 1 : 0
        if (record.defect != '' || record.defect != undefined || record.defect != null) {
          dataForm.defect = record.defect.split(',')
        }

        pageData.sideTitle = '修改'
        pageData.showAdd = true
      }

      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        //flex: 1
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)

      const focusSelopen7 = () => {
        selCxAllopen7({ defectName: '' })
      }
      const optionsopen7 = ref<any>(pageData.nameOpen7)
      const loading7 = ref(false)
      const handleSearchopen7 = (value: any) => {
        if (value) {
          const ob = { defectName: value, deleteState: 0 }
          loading7.value = true
          selCxAllopen7(ob)
          optionsopen7.value = pageData.nameOpen7
          loading7.value = false
        } else {
          optionsopen7.value = []
        }
      }

      function selCxAllopen7(val: any) {
        post({
          url: 'qms/defectType/select',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.nameOpen7 = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          // EXELTABLE(tc, gridOption.value.getSelectedRows().map((res: any) => {
          //     // res['state'] = (res.state == 0 ? "未录入" : "已录入")
          //     delete res.state
          // }), '坯布疵点预防措施')
          EXELTABLE(tc, gridOption.value.getSelectedRows(), '坯布疵点预防措施')
        }
      }
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/planSingle/greyDefect/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/planSingle/greyDefect/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '坯布疵点预防措施.xlsx')
            }
          })
      }
      const focusSel1 = () => {
        selCxAllopen2({ grayFabricName: '' })
      }
      const optionsopen1 = ref<any>(pageData.nameOpen2)
      const loading1 = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { grayFabricName: value }
          loading1.value = true
          selCxAllopen2(ob)
          optionsopen1.value = pageData.nameOpen2
          loading1.value = false
        } else {
          optionsopen1.value = []
        }
      }

      function selCxAllopen2(val: any) {
        post({
          url: '/product/pdGreyInformation/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.nameOpen2 = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const focusSel = () => {
        selCxAllopen({ greyCode: '' })
      }
      const optionsopen4 = ref<any>(pageData.nameOpen1)
      const loading4 = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { greyCode: value }
          loading4.value = true
          selCxAllopen(ob)
          optionsopen4.value = pageData.nameOpen1
          loading4.value = false
        } else {
          optionsopen4.value = []
        }
      }

      function selCxAllopen(val: any) {
        post({
          url: '/product/pdGreyInformation/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.nameOpen1 = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('PreventiveMeasure-1', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('pbcdyfcs.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('pbcdyfcs.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('pbcdyfcs.drExcel')) {
        pageData.btnList.push('导入')
      }
      if (permissionStore.hasPermisson('pbcdyfcs.mbxz')) {
        pageData.btnList.push('模板下载')
      }
      if (permissionStore.hasPermisson('pbcdyfcs.xg')) {
        pageData.isEdit = true
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        loading1,
        loading4,
        loading7,
        focusSel1,
        handleSearch1,
        focusSel,
        handleSearch,
        downloadHandler,
        importHandler,
        exports,
        focusSelopen7,
        handleSearchopen7,
        headerShow,
        pagingList1,
        huiche,
        localeText1,
        scroll,
        scrollbar,
        tablediv,
        hasChiese,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        editHandler,
        selectHandler,
        PageSize,
        change1,
        handleChange,
        defaultColDef,
        tc,
        gridOption,
        gridReady,
        total,
      }
    },
    components: { Toolbar,  },
  }
</script>
